package com.tycmc.signelectroniccontracts.tools.net.tools;

import android.content.Context;
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class SSLWebViewClient extends WebViewClient {
    private X509Certificate[] certificatesChain;
    private PrivateKey clientCertPrivateKey;

    byte[] certfile_p12;
    private String certfile_password = "";

    public SSLWebViewClient(Context context, byte[] cert, String pass) throws Exception {
        super();

        certfile_password = pass;
        certfile_p12 = cert;

        initPrivateKeyAndX509Certificate();
    }

    private void initPrivateKeyAndX509Certificate() throws Exception {
        KeyStore keyStore;
        keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(DataTools.byteTOInputStream(certfile_p12), certfile_password.toCharArray());
        Enumeration<?> localEnumeration;
        localEnumeration = keyStore.aliases();
        while (localEnumeration.hasMoreElements()) {
            String str3 = (String) localEnumeration.nextElement();
            clientCertPrivateKey = (PrivateKey) keyStore.getKey(str3, certfile_password.toCharArray());
            if (clientCertPrivateKey == null) {
                continue;
            } else {
                Certificate[] arrayOfCertificate = keyStore.getCertificateChain(str3);
                certificatesChain = new X509Certificate[arrayOfCertificate.length];
                for (int j = 0; j < certificatesChain.length; j++) {
                    certificatesChain[j] = ((X509Certificate) arrayOfCertificate[j]);
                }
            }
        }

    }

//    public void onReceivedClientCertRequest(WebView view,
//                                            ClientCertRequestHandler handler, String host_and_port) {
//        if((null != clientCertPrivateKey) && ((null!=certificatesChain) && (certificatesChain.length !=0))){
//            handler.proceed(this.clientCertPrivateKey, this.certificatesChain);
//        }else{
//            handler.cancel();
//        }
//    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onReceivedSslError(final WebView view, SslErrorHandler handler,
                                   SslError error) {
        handler.proceed();
    }


}
